package cn.com.demo.keystore;

import cn.com.demo.cert.X509CertificateExample;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.security.auth.x500.X500PrivateCredential;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate;

public class PKCS12KeyStoreExample {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static KeyStore createKeyStore() throws Exception {
        KeyStore store = KeyStore.getInstance("PKCS12", "BC");

        //initialize
        store.load(null, null);

        X500PrivateCredential rootCredential = X509CertificateExample.generateRootCredetial();
        X500PrivateCredential interCredential = X509CertificateExample.generateIntermediateCredential(
                rootCredential.getPrivateKey(), rootCredential.getCertificate());
        X500PrivateCredential endCredential = X509CertificateExample.generateEndCredential(interCredential.getPrivateKey(),
                interCredential.getCertificate());

        X509Certificate[] chain = new X509Certificate[3];
        chain[0] = endCredential.getCertificate();
        chain[1] = interCredential.getCertificate();
        chain[2] = rootCredential.getCertificate();

        //set the entries
        store.setCertificateEntry(rootCredential.getAlias(), rootCredential.getCertificate());

        store.setKeyEntry(endCredential.getAlias(), endCredential.getPrivateKey(), null, chain);

        return store;
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        KeyStore store = createKeyStore();
        char[] password = "5751A28AC5F78387".toCharArray();

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        //save the store
        store.store(bOut, password);
        FileOutputStream fos = new FileOutputStream(new File("D:/bjcaTest.jks"));
        fos.write(bOut.toByteArray());
        fos.close();
        bOut.close();
        //reload from scratch
//		store = KeyStore.getInstance("PKCS12","BC");
//		store.load(new ByteArrayInputStream(bOut.toByteArray()), password);
//		
//		Enumeration<String> e = store.aliases();
//		while (e.hasMoreElements()) {
//			String alias = (String) e.nextElement();
//			System.out.println("found " + alias 
//					+ ", isCertificate ? " + store.isCertificateEntry(alias)
//					);
//		}
    }

}
